package com.huajin.iot.common.service;


import org.apache.http.HttpHost;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 
 * @author ke
 *
 */


public class EsDataSource {

	/**
	 * 数据源rest client
	 */
	private RestClient esClient;

	
	
	/**
	 * 程序开始时初始化elasticsearch连接，结束时关闭连接
	 */
	public EsDataSource(String ips) {
		try {
			esClient = this.connectionInit(ips);
			getClientInfo(esClient);

		} catch (Exception e) {
			this.doShutdownWork();
			//log.error(e.getMessage(), e);
			System.exit(-1);
		}
		this.doShutdownWork();
	}


	private RestClient connectionInit(String ips) {
		String[] hosts = ips.split(",");
		List<HttpHost> hostList = new ArrayList<>(hosts.length);
		for (String ip : hosts) {
			String[] host = ip.split(":");
			hostList.add(new HttpHost(host[0], Integer.parseInt(host[1])));
		}
		return RestClient.builder(hostList.toArray(new HttpHost[hosts.length])).build();
	}

	private void doShutdownWork() {
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					esClient.close();
				} catch (IOException e) {
					//log.error(e.getMessage(), e);
				}

			}
		}));
	}

	public RestClient getEsClient() {
		return esClient;
	}



	public void getClientInfo(RestClient client) throws IOException {
		Response resp = client.performRequest("GET", "", Collections.<String, String>emptyMap());
		//log.info("\n{}", EntityUtils.toString(resp.getEntity()));
	}
	
}
